<template>
  <div class="app-container">
    <el-row>
      <!-- 顶部搜索栏 -->
      <el-form ref="queryForm" :model="queryParams" v-show="showSearch" :inline="true">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable  style="width: 240px">
          </el-input>
        </el-form-item>
        <el-form-item label="图案" prop="pattern">
          <el-select v-model="queryParams.pattern" placeholder="请选择">
            <el-option
              v-for="item in patternOptions"
              :key="item.patternId"
              :label="item.patternName"
              :value="item.patternId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上传人" prop="uploadUser">
          <el-input v-model="queryParams.uploadUser" placeholder="请输入上传人" clearable  style="width: 240px">
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表头按钮组 -->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:user:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
          >导入</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
      </el-row>

      <!-- 后台回显表格 -->
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="产品编号" align="center" key="productId" prop="productId" v-if="columns[0].visible"  />
        <el-table-column label="产品名称" align="center" key="productName" prop="productName" v-if="columns[1].visible" :show-overflow-tooltip="true" />
        <el-table-column label="图案编号" align="center" key="pattern" prop="pattern" v-if="columns[2].visible" :show-overflow-tooltip="true" />
        <el-table-column label="上传人" align="center" prop="uploadUser" v-if="columns[3].visible" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            {{ scope.row.users[0].nickName }}
          </template>
        </el-table-column>
        <el-table-column label="上传日期" align="center" prop="uploadDate" v-if="columns[4].visible" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.uploadDate }}</span>
          </template>
        </el-table-column>
        <el-table-column label="图案" align="center" prop="patterns" v-if="columns[7].visible" width="160">
          <template slot-scope="scope">
<!--            <span v-for="(u,i) in scope.row.patterns"><img v-bind:src="imgurl + u.patternImgUrl" style="max-width: 100%;height: auto;"></span>-->
            <img v-bind:src="imgurl + scope.row.patterns[0].patternImgUrl" style="max-width: 100%;height: 30px;" />
          </template>
        </el-table-column>
        <el-table-column label="更改人" align="center" key="modifyUser" prop="modifyUser" v-if="columns[5].visible" width="120" />
        <el-table-column label="更改日期" align="center" prop="modifyDate" v-if="columns[6].visible" width="160">
          <template slot-scope="scope">
            <span>{{ scope.row.modifyDate }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="160"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope" v-if="scope.row.productId !== 1">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部pagination -->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图案编号" prop="pattern">
<!--              <el-input v-model="form.pattern" placeholder="请输入图案" maxlength="30" />-->
              <el-select v-model="form.pattern" placeholder="请选择">
                <el-option
                  v-for="item in patternOptions"
                  :key="item.patternId"
                  :label="item.patternName"
                  :value="item.patternId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的产品与图案数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import { listProduct, getProduct, addProduct, updateProduct, delProduct, importTemplate, exportProduct} from '@/api/wire/pap/product/product'
import { listPattern } from '@/api/wire/pap/pattern/pattern'

export default {
  name: "Product",
  data() {
    return {
      //图片地址前缀
      imgurl:process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      productNames:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //产品数据
      productList: null,
      // 弹出层标题
      title: "",
      // 图案选项
      patternOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        pattern: undefined,
        uploadUser: undefined,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/product/importProduct"
      },
      // 列信息
      columns: [
        { key: 0, label: `图案序号`, visible: false },
        { key: 1, label: `产品名称`, visible: true },
        { key: 2, label: `图案编号`, visible: true },
        { key: 3, label: `上传人`, visible: true },
        { key: 4, label: `上传日期`, visible: true },
        { key: 5, label: `更改人`, visible: false },
        { key: 6, label: `更改日期`, visible: false },
        { key: 7, label: `图案`, visible: true , name: 'patternImgUrl' },
      ],
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        pattern: [
          { required: true, message: "图案不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getPatternList();
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
          this.productList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    /** 获取当前数据库中所有图案作为下拉选择 */
    getPatternList() {
      this.loading = true;
      listPattern().then(response => {
          this.patternOptions = response.rows;
        }
      );
    },
    // 表单重置
    reset() {
      this.form = {
        productId: undefined,
        productName: undefined,
        pattern: undefined,
        uploadUser: undefined,
        uploadDate: undefined,
        modifyUser: undefined,
        modifyDate: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      listPattern().then(response => {
          this.patternOptions = response.rows;    //获取当前数据库中所有图案作为下拉选择

          getProduct().then(response => {
            this.open = true;
            this.title = "添加产品";
          });
        }
      );
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const productId = row.productId || this.ids;
      listPattern().then(response => {
          this.patternOptions = response.rows;    //获取当前数据库中所有图案作为下拉选择

          getProduct(productId).then(response => {
            this.form = response.data;
            this.open = true;
            this.title = "修改用户";
          });
        }
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.productId || this.ids;
      const productNames = row.productName || this.productNames;

      this.$confirm('是否确认删除产品名称为"' + productNames + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delProduct(productIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有产品与图案数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportProduct(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 多选框选中数据 **/
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId);
      this.productNames = selection.map(item => item.productName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增/修改 对话框提交按钮 */
    submitForm: function() {
      console.log(this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.productId != undefined) {
            updateProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              // this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              // this.getList();
            });
          }
        }
      });
    },
    /** 新增对话框取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
  },
}
</script>

<style scoped>

</style>
